#!/bin/bash

sandboxdir=$(dirname $0)
. $sandboxdir/sb_vars.sh
. $sandboxdir/sb_common.sh

pre_installation fanin

if [ -n "$1" ]
then
    export HOW_MANY_NODES=$1
fi

if [ $HOW_MANY_NODES -lt 3 ]
then
    echo "At least 3 nodes are required for a fanin topology"
    exit 1
fi

$sandboxdir/sb_make_sandboxes
check_exit_code

if [ -n "$USE_INI" ]
then
    install_with_ini_files
else
    SERVICE_INDEX=0


    for NODE in $(seq 1 $(($HOW_MANY_NODES-1)))
    do
        DELTA=$(($NODE*10))
        THL_PORT=$(($THL_BASE_PORT+$DELTA))
        configure_defaults $NODE
        MASTER_SERVICE=${MM_SERVICES[$SERVICE_INDEX]}
        configure_master $MASTER_SERVICE $THL_PORT
        tpm_install
        SERVICE_INDEX=$(($SERVICE_INDEX+1))
    done

    SLAVE_SERVICE_INDEX=0
    FANIN_SLAVE=$HOW_MANY_NODES
    configure_defaults $FANIN_SLAVE

    SLAVE_SERVICE_INDEX=0
    for SLAVENODE in $(seq 1 $(($HOW_MANY_NODES-1)))
    do
        SLAVEDELTA=$(($SLAVENODE*10))
        SLAVE_THL_PORT=$(($THL_BASE_PORT+$SLAVEDELTA))
        SLAVE_SERVICE=${MM_SERVICES[$SLAVE_SERVICE_INDEX]}
        configure_slave $SLAVE_SERVICE $SLAVE_THL_PORT
        SLAVE_SERVICE_INDEX=$(($SLAVE_SERVICE_INDEX+1))
    done
    tpm_install
fi

post_installation fanin
